<?	/*
	// File		 :	virtualqmail.wcp.phps
	// Purpose	 :	Manage virtual mail domains on qmail using vqmail tools.
	// Author	 :	Jared Hewitt <jhewitt@blackrak.com>
	// Credits	 :	|* based on original qmail hack by Johan *|
	// Comment	 :	We're going to use vpopmail commands here to manage virtual domains/users
        //                      So the vqmail tools should be installed (at least vpopmail). This is a must!!!
	//
	// Qmail-Install :	I recommend using qmailrocks.com for your qmail installation.
	//
	// Misc		 :	If you contributed to these scripts and would like to be listed in the credits
	//			please send an email to jhewitt@blackrak.com, explaining what you contributed
	//			and how you would like to be referred to in the credits.
	*/


// Handle email domain manipulation
if ($type == "domain") {

	// Create Domain :: expect *
	if ($data['action'] == "create") {

		// First check to see if it's a pointer, and if it is, set it up here.
		if ( $data['type'] == 'pointer' ) {
			// :: point @domain-pointer.com to >> @main-domain.com
			$dbp = mysql_query("SELECT DISTINCT domain FROM domains WHERE id='".$data['owner']."'");
			$ddata = mysql_fetch_array($dbp);
			exec($cfg['prog']['vaddaliasdomain']." ".$data['domain']." ".$ddata['domain']);

		// If not check to make sure it's not a subdomain. Subdomains don't need to be set up with qmail.
		} elseif ( $data['type'] != 'subdomain' ) {
                	exec($cfg['prog']['vadddomain']." ".$data['domain']." ".$cfg['vqmail_postmaster_passwd']);
		}
	}

	// Update Domain :: expect *
	if ($data['action'] == "update") {

		// Check to see if we're updating a pointer domain, and if so do it.
		if ( $data['type'] == 'pointer' ) {

			if ($data['domain'] != $data['domain1']) {

				// :: point @domain-pointer.com to >> @main-domain.com
				// Manualy change 3 files ( $cfg['qmail_rpchosts'] $cfg['qmail_virtdomains'] $cfg['qmail_assign'] )
				// because vdelaliasdomain doesn't currently exist and there's no better way to do it.

				// Change $cfg['qmail_rpchosts']

				// Load current files
				$sysfile['qmail_rpchosts'] = file_get_contents($cfg['qmail_rpchosts']);
				// Change domain
				$sysfile['qmail_rpchosts'] = str_replace($data['domain1'], $data['domain'], $sysfile['qmail_rpchosts']);

				// Write change
				file_put_contents($cfg['qmail_rpchosts'],$sysfile['qmail_rpchosts']);

				// Change $cfg['qmail_virtdomains']

				// Load current files
				$sysfile['qmail_virtdomains'] = file_get_contents($cfg['qmail_virtdomains']);
				// Change domain
				$sysfile['qmail_virtdomains'] = str_replace($data['domain1'], $data['domain'], $sysfile['qmail_virtdomains']);

				// Write change
				file_put_contents($cfg['qmail_virtdomains'],$sysfile['qmail_virtdomains']);

				// Change $cfg['qmail_assign']
				// Load current files
				$sysfile['qmail_assign'] = file_get_contents($cfg['qmail_assign']);
				// Change domain
				$sysfile['qmail_assign'] = str_replace($data['domain1'], $data['domain'], $sysfile['qmail_assign']);

				// Write change
				file_put_contents($cfg['qmail_assign'],$sysfile['qmail_assign']);
			}

		// Check to see if we're changing a domain name and if so make the changes.
		} elseif ( $data['type'] != 'subdomain' ) {
			if ($data['domain'] != $data['domain1']) {

					// Create a new domain
					exec($cfg['prog']['vadddomain']." ".$data['domain']." ".crypt($data['password'],$cfg['key']));

					// Add users
					$dbp = mysql_query("SELECT DISTINCT u.aliases,u.username FROM users u, domains d WHERE d.id='".$data['id']."' AND d.id=u.id");
					while ($ddata = mysql_fetch_array($dbp)) {
						// Add every users to that domain
						exec($cfg['prog']['vadduser']." ".$ddata['username']."@".$data['domain']." norealpass");

						// Copy old user directory to the new one
						exec($cfg['prog']['rm']." -rf ".$cfg['vqmail_domains']."/".$data['domain']."/".$ddata['username']);
						exec($cfg['prog']['cp']." -Rf ".$cfg['vqmail_domains']."/".$data['domain1']."/".$ddata['username']." ".$cfg['vqmail_domains']."/".$data['domain']."/");
					}

					// Copy password file (and delete vpasswd.cdb to be able to keep old password)
					exec($cfg['prog']['rm']." -f ".$cfg['vqmail_domains']."/".$data['domain']."/vpasswd");
					exec($cfg['prog']['rm']." -f ".$cfg['vqmail_domains']."/".$data['domain']."/vpasswd.cdb");

					// Change new directory into vpasswd file
					exec($cfg['prog']['sed']." -e \"s/".
					str_replace("/", "\/", quotemeta($cfg['vqmail_domains']."/".$data['domain1']))."/".
					str_replace("/", "\/", quotemeta($cfg['vqmail_domains']."/".$data['domain']))."/g\" ".
					$cfg['vqmail_domains']."/".$data['domain1']."/vpasswd > ".
					$cfg['vqmail_domains']."/".$data['domain']."/vpasswd");

					// change directory owner
					exec($cfg['prog']['chown']." -R ".$cfg['vqmail_user'].":".$cfg['vqmail_group']." " .$cfg['vqmail_domains']."/".$data['domain']);

					// Delete old domain
					exec($cfg['prog']['vdeldomain']." ".$data['domain1']);
			}
		}
	}

	// Remove Domain :: expect username
	if ($data['action'] == "remove") {

		// Check to make sure we're not just removing a subdomain.
		if ( $data['type'] != 'subdomain' ) {

			// Delete domain first then check for pointers and if they exist delete them.
			exec($cfg['prog']['vdeldomain']." ".$data['domain']);

			$dbp = mysql_query("SELECT * FROM domains WHERE owner='".$data['id']."'");
			if ( mysql_num_rows($dbp) != 0 ){

            	// Manualy change 3 files ( $cfg['qmail_rpchosts'] $cfg['qmail_virtdomains'] $cfg['qmail_assign'] )
            	// because vdelaliasdomain doesn't currently exist and there's no better way to do it.

				// Load current files
				$sysfile['qmail_rpchosts'] = file($cfg['qmail_rpchosts']);
				$sysfile['qmail_virtdomains'] = file($cfg['qmail_virtdomains']);
				$sysfile['qmail_assign'] = file($cfg['qmail_assign']);

				while ($ddata = mysql_fetch_array($dbp)) {

					// Clear old newfile
					if ( isset($newfile) ) {
					unset($newfile);
					}

					// Set newfiles as array
					$newfile['qmail_rpchosts'] = array();
					$newfile['qmail_virtdomains'] = array();
					$newfile['qmail_assign'] = array();

					// Delete ligne in $cfg['qmail_rpchosts']
					while ( list($line_num, $line) = each($sysfile['qmail_rpchosts'])) {
						if (( substr_count($line, $ddata['domain']) == 0 ) AND ( in_array($line, $newfile['qmail_rpchosts']) == FALSE ))
						{
							array_push($newfile['qmail_rpchosts'], $line);
						}
					}
					$sysfile['qmail_rpchosts'] = $newfile['qmail_rpchosts'];

					// Delete ligne in $cfg['qmail_virtdomains']
					while ( list( $line_num, $line ) = each( $sysfile['qmail_virtdomains'] ) ) {
						if (( substr_count($line, $ddata['domain']) == 0 ) AND ( in_array($line, $newfile['qmail_virtdomains']) == FALSE ))
						{
							array_push($newfile['qmail_virtdomains'], $line);
						}
					}
					$sysfile['qmail_virtdomains'] = $newfile['qmail_virtdomains'];

					// Delete ligne in $cfg['qmail_assign']
					while ( list( $line_num, $line ) = each( $sysfile['qmail_assign'] ) ) {
						if (( substr_count($line, $ddata['domain']) == 0 ) AND ( in_array($line, $newfile['qmail_assign']) == FALSE ))
						{
							array_push($newfile['qmail_assign'], $line);
						}
					}
					$sysfile['qmail_assign'] = $newfile['qmail_assign'];
				}

				// Write $cfg['qmail_rpchosts'] change
				$sysfile['qmail_rpchosts'] = implode('', $sysfile['qmail_rpchosts']);
				file_put_contents($cfg['qmail_rpchosts'],$sysfile['qmail_rpchosts']);

				// Write $cfg['qmail_virtdomains'] change
				$sysfile['qmail_virtdomains'] = implode('', $sysfile['qmail_virtdomains']);
				file_put_contents($cfg['qmail_virtdomains'],$sysfile['qmail_virtdomains']);

				// Write $cfg['qmail_assign'] change
				$sysfile['qmail_assign'] = implode('', $sysfile['qmail_assign']);
				file_put_contents($cfg['qmail_assign'],$sysfile['qmail_assign']);
			}
		}
	}
}

// Handle user manipulation
if ($type == "user") {

	// Create User :: expect *
	if ($data['action'] == "create") {

		// Get the domain that the user belongs to.
		$dbp = mysql_query("SELECT DISTINCT domain FROM domains WHERE id='".$data['id']."'");
		$ddata = mysql_fetch_array($dbp);

		// Add the user via vadduser.
		exec($cfg['prog']['vadduser']." ".$data['username']."@".$ddata['domain']." ".escapeshellarg($data['password']));

		// Create Aliases.
		$linkfile['aliases'] = $cfg['vqmail_domains']."/".$ddata['domain']."/.qmail-";
		$data['aliases'] = trim($data['aliases']);
		if (strstr($data['aliases']," ")) {
			$aliases = explode(" ",$data['aliases']);
			while (current($aliases)) {
				$realfile = $linkfile['aliases'].str_replace(".",":",current($aliases));
				file_put_contents($realfile,$data['username']."@".$ddata['domain']);
				// Set the write owner
				exec($cfg['prog']['chown']." ".$cfg['vqmail_user'].":".$cfg['vqmail_group'].
					" ".$realfile);

				next($aliases);
			}

		}
		elseif ($data['aliases']) {

			// Check if it's a new alias and if so create it.
			$realfile = $linkfile['aliases'].str_replace(".",":",$data['aliases']);
			file_put_contents($realfile,$data['username']."@".$ddata['domain']);

			// Set the correct owner.
			exec($cfg['prog']['chown']." ".$cfg['vqmail_user'].":".$cfg['vqmail_group'].
				" ".$realfile);
		}
	}

	// Update User :: expect *
	if ($data['action'] == "update") {

		// Get domain the user belongs to.
		$dbp = mysql_query("SELECT DISTINCT domain, domain1 FROM domains WHERE id='".$data['id']."'");
		$ddata = mysql_fetch_array($dbp);

		// Check to see if we're changing the username and if so chenge their mail account to match.
		if ($data['username'] != $data['username1']) {

			// First we create a new user.
			exec($cfg['prog']['vadduser']." ".$data['username']."@".$ddata['domain']." ".escapeshellarg($data['password']));

			// Then we delete the new directory.
			exec($cfg['prog']['rm']." -rf ".$cfg['vqmail_domains']."/".$ddata['domain']."/".$data['username']);

			// Copy the old directory over to the directory name of the new user.
			exec($cfg['prog']['cp']." -R ".$cfg['vqmail_domains']."/".$ddata['domain']."/".$data['username1']." ".
				$cfg['vqmail_domains']."/".$ddata['domain']."/".$data['username']);

			// Change directory to the correct owner.
			exec($cfg['prog']['chown']." -R ".$cfg['vqmail_user'].":".$cfg['vqmail_group']." " .$cfg['vqmail_domains']."/".$ddata['domain']."/".$data['username']);

			// Delete old user
			exec($cfg['prog']['vdeluser']." ".$data['username1']."@".$ddata['domain']);

			// Move the aliases file.
			// To decrease the chance of error (mainly something being overlooked) this function is done in two places. Once here and again below.
			if ( file_exists($cfg['vqmail_domains']."/".$ddata['domain']."/.qmail-".$data['username1']) ) {
				exec($cfg['prog']['mv']." ".$cfg['vqmail_domains']."/".$ddata['domain']."/.qmail-".$data['username1'].
					" ".$cfg['vqmail_domains']."/".$ddata['domain']."/.qmail-".$data['username']);
			}
		}

		// Set the mailbox to Catch-All if selected.
		$linkfile['catchall'] = $cfg['vqmail_domains']."/".$ddata['domain']."/.qmail-default";
		$dbp = mysql_query("SELECT username FROM users WHERE catchall = 'true' and id = '".$data['id']."'");
		$udata = mysql_fetch_array($dbp);
		if ( $data['catchall'] == "true" && $udata['username'] == "" ) {
			file_put_contents($linkfile['catchall'],"| ".$cfg['prog']['vdelivermail']." '' ".$data['username']."@".$ddata['domain']);
		} else {
			// Check to see if a catchall no longer exists for this domain. If it doesn't change .qmail-default to reflect this.
			if ( $udata['username'] == "" ) {
					file_put_contents($linkfile['catchall'],"| ".$cfg['prog']['vdelivermail']." '' bounce-no-mailbox");
			}
		}
		// Set the correct owner.
		exec($cfg['prog']['chown']." ".$cfg['vqmail_user'].":".$cfg['vqmail_group']." ".$linkfile['catchall']);

		// Check the aliases directory for files.
		$linkfile['aliases_dir'] = $cfg['vqmail_domains']."/".$ddata['domain'];
		$linkfile['aliases'] = $linkfile['aliases_dir']."/.qmail-";
		$localaliases = array();
		if ($dir = @opendir($linkfile['aliases_dir'])) {
		  while($file = readdir($dir)) {

			// Check to see if it is in fact and alias file.
			if ( substr_count($file, ".qmail-") )
			{
				// Next check to see if it contains the current username.
				$realfile = $linkfile['aliases_dir']."/".$file;
				if 	( $data['username']."@".$ddata['domain'] == file_get_contents($realfile) )
				{
					// If everything checks out, add the alias to the list.
					array_push($localaliases, $file);
				}
			}
		  }
		  closedir($dir);
		}

		// Get new aliases and remove the old ones.
		$data['aliases'] = trim($data['aliases']);
		if (strstr($data['aliases']," ")) {
			$aliases = explode(" ",$data['aliases']);

			// Find any old aliases.
			while (current($localaliases)) {
				$tmp = false;
				// If the alias no longer exists, remove it.
				while (current($aliases)) {
					// We know that ".qmail-" is 7 char.
					if ( current($aliases) == str_replace(":",".",substr(current($localaliases),7))) {
						$tmp = true;
						break;
					}
					next($aliases);
				}
				if ($tmp == false) {
					unlink($linkfile['aliases_dir']."/".current($localaliases));
				}
				next($localaliases);
			}

			// Find any new aliases.
			while (current($aliases)) {
				$realfile = $linkfile['aliases'].str_replace(".",":",current($aliases));
				if ( file_exists($realfile) ) {
					$sysfile['aliases'] = file_get_contents($realfile);
				} else {
					$sysfile['aliases'] = "";
				}

				$newfile['aliases'] = $data['username']."@".$ddata['domain'];

				// If everything checks out, write it to the file.
				if ($newfile['aliases'] != $sysfile['aliases']) {
					file_put_contents($realfile,$newfile['aliases']);
					// Set the correct owner.
					exec($cfg['prog']['chown']." ".$cfg['vqmail_user'].":".$cfg['vqmail_group'].
						" ".$realfile);
				}

				next($aliases);
			}
		}
		elseif ($data['aliases']) {
			// Find any old aliases
			while (current($localaliases)) {
				// If alias no longer exists remove it. We know that ".qmail-" is 7 char.
				if ( $data['aliases'] != str_replace(":",".",substr(current($localaliases),7))) {
					unlink($linkfile['aliases_dir']."/".current($localaliases));
				}
				next($localaliases);
			}

			// If it's a new alias, create it.
			$realfile = $linkfile['aliases'].str_replace(".",":",$data['aliases']);
			if ( file_exists($realfile) ) {
				$sysfile['aliases'] = file_get_contents($realfile);
			} else {
				$sysfile['aliases'] = "";
			}

			$newfile['aliases'] = $data['username']."@".$ddata['domain'];

			// If everything checks out, write it to the file.
			if ($newfile['aliases'] != $sysfile['aliases']) {
				file_put_contents($realfile,$newfile['aliases']);
				// Set the write owner
				exec($cfg['prog']['chown']." ".$cfg['vqmail_user'].":".$cfg['vqmail_group'].
					" ".$realfile);
			}
		}

		// Set up forwards.
		$linkfile['forward'] = $cfg['vqmail_domains']."/".$ddata['domain']."/".$data['username']."/.qmail";

		// Load current files.
		if ( file_exists($linkfile['forward']) ) {
			$sysfile['forward'] = file_get_contents($linkfile['forward']);
		} else {
			$sysfile['forward'] = "";
		}

		// Get forward information.
		$data['forward'] = trim($data['forward']);
		if (strstr($data['forward']," ")) {
			$forward = explode(" ",$data['forward']);
			while (current($forward)) {
				$newfile['forward'] .= current($forward)."\n";
				next($forward);
			}
		}
		elseif ($data['forward']) {
				$newfile['forward'] .= $data['forward']."\n";
		}

		// Write the forward info into the file, or unlink it if it doesn't exist.
		if ( empty($newfile['forward']) ) {
			if ( is_file($linkfile['forward']) ) {
				unlink($linkfile['forward']);
			}
		}
		elseif ($newfile['forward'] != $sysfile['forward']) {
			file_put_contents($linkfile['forward'],$newfile['forward']);
			// Set the correct owner.
			exec($cfg['prog']['chown']." ".$cfg['vqmail_user'].":".$cfg['vqmail_group']." ".$linkfile['forward']);
		}

		// Set up autoreply.
		$linkfile['autorespond_userdir'] = $cfg['vqmail_domains']."/".$ddata['domain']."/".$data['username'];
		$linkfile['autorespond_qmail'] = $linkfile['autorespond_userdir']."/.qmail";
		$linkfile['autorespond_dir'] = $linkfile['autorespond_userdir']."/vacation";
		$linkfile['autorespond_maildir'] = $linkfile['autorespond_userdir']."/Maildir";
		$linkfile['autorespond_msg'] = $linkfile['autorespond_dir']."/message";

		// Here we set up some basic stuff.
		if ($data['autoreply']) {
			// Create the vacation directory if it doesn't exist.
			if ( !is_dir($linkfile['autorespond_dir']) ) {
				mkdir ($linkfile['autorespond_dir'], 0700);
			}

			// Create or change the response message.
			$newfile['msg'] = "From: ".$data['username']."@".$ddata['domain']."\n\n";
			$newfile['msg'] .= "Subject: "."Re: Autoreply"."\n\n";
			$newfile['msg'] .= $data['autoreply'];

			// Once set up, write the information to the file.
			file_put_contents($linkfile['autorespond_msg'],substr($newfile['msg'],0,10240)); // limit autoreply to 10k

			// Respectively change the .qmail file.
			$tmptxt = "| ".$cfg['prog']['autorespond']." 86400 3 ".$linkfile['autorespond_msg'].
				" ".$linkfile['autorespond_dir']." \n".$linkfile['autorespond_maildir'];

			$newfile['qmail'] = array();

			if ( is_file($linkfile['qmail']) ) {
				// Load current files.
				$sysfile['qmail'] = file($linkfile['autorespond_qmail']);

				// Delete the autorespond line.
				while ( list($line_num, $line) = each($sysfile['qmail'])) {
					if (( substr_count($line, $cfg['prog']['autorespond']) == 0 ))
					{
						array_push($newfile['qmail'], $line);
					}
				}
			}

			// Add our tmptxt to the .qmail file.
			array_push($newfile['qmail'],$tmptxt);

			$newfile['qmail'] = join('', $newfile['qmail']);

			// Save info to file or unlink it if no nothing is set.
			if ( empty($newfile['qmail']) ) {
				if ( is_file($linkfile['qmail']) ) {
					unlink($linkfile['qmail']);
				}
			}
			elseif ($newfile['qmail'] != $sysfile['qmail']) {
				file_put_contents($linkfile['autorespond_qmail'],$newfile['qmail']);
			}

			// Set the correct owner.
			exec($cfg['prog']['chown']." -R ".$cfg['vqmail_user'].":".$cfg['vqmail_group'].
				" ".$linkfile['autorespond_userdir']);

		} else {
			// Remove the  vacation directory if it exists.
			if ( is_dir($linkfile['autorespond_dir']) ) {
				exec($cfg['prog']['rm']." -rf ".$linkfile['autorespond_dir']);
			}

			if ( is_file($linkfile['autorespond_qmail'])) {

				// Load the current files.
				$sysfile['qmail'] = file($linkfile['autorespond_qmail']);

				$newfile['qmail'] = array();

				// Delete the autorespond line.
				while ( list($line_num, $line) = each($sysfile['qmail'])) {
					if (( substr_count($line, $cfg['prog']['autorespond']) == 0 )) {
						array_push($newfile['qmail'], $line);
					}
				}

				// If everything checks out write it to the file.
				$newfile['qmail'] = join('', $newfile['qmail']);
				if ($newfile['qmail'] != $sysfile['qmail']) {
					file_put_contents($linkfile['autorespond_qmail'],$newfile['qmail']);
					// Set the correct owner.
					exec($cfg['prog']['chown']." ".$cfg['vqmail_user'].":".$cfg['vqmail_group'].
						" ".$linkfile['autorespond_qmail']);
				}
			}

		}
	}

	// Remove User :: expect username
	if ($data['action'] == "remove") {

		// Get the domain the user belongs to.
		$dbp = mysql_query("SELECT DISTINCT domain FROM domains WHERE id='".$data['id']."'");
		$ddata = mysql_fetch_array($dbp);

		// Remove the user via vdeluser.
		exec($cfg['prog']['vdeluser']." ".$data['username']."@".$ddata['domain']);

		// Remove Catch-All
		// Check to see if a catchall no longer exists for this domain. If it doesn't change .qmail-default to reflect this.
		$dbp = mysql_query("SELECT username FROM users WHERE catchall = 'true' and id = '".$data['id']."'");
		$udata = mysql_fetch_array($dbp);
		if ( $udata['username'] == $data['username'] ) {
			file_put_contents($cfg['vqmail_domains']."/".$ddata['domain']."/.qmail-default","| ".$cfg['prog']['vdelivermail']." '' bounce-no-mailbox");
			// Set the correct owner.
			exec($cfg['prog']['chown']." ".$cfg['vqmail_user'].":".$cfg['vqmail_group'].
				" ".$cfg['vqmail_domains']."/".$ddata['domain']."/.qmail-default");
		}

		// Remove the alias file for the user.
		if ($dir = @opendir($cfg['vqmail_domains']."/".$ddata['domain'])) {
		  while($file = readdir($dir)) {
			// Check to make sure the file is in fact an alias file.
			if ( substr_count($file, ".qmail-") )
			{
				// Check to make sure it contains the correct username.
				$realfile = $cfg['vqmail_domains']."/".$ddata['domain']."/".$file;
				if 	( $data['username']."@".$ddata['domain'] == file_get_contents($realfile) )
				{
					// Unlink the file.
					unlink($realfile);
				}
			}
		  }
		  closedir($dir);
		}
	}
}

?>